<template>
    <div class="g-container">


        <el-row>
            <el-col :span="20">
                <h1>域名:{{ domain.name }}</h1>
            </el-col>
            <el-col :span="4" class="btns-right">
                <el-button type="primary" @click="editHandle()">增加</el-button>
            </el-col>
        </el-row>


        <el-table
                border
                class="g-table"
                element-loading-spinner="el-icon-loading"
                :data="records">
            <el-table-column label="No." align="center" type="index" width="50"/>
            <el-table-column
                    align="center"
                    label="主机记录"
                    prop="name"/>
            <el-table-column
                    align="center"
                    label="类型"
                    width="100"
                    prop="type"/>
            <el-table-column
                    align="center"
                    label="记录值"
                    prop="value"/>
            <el-table-column
                    align="center"
                    label="TTL"
                    width="100"
                    prop="ttl">
                <template v-slot="{row}">
                    {{ fmtTtl(row.ttl) }}
                </template>
            </el-table-column>
            <el-table-column
                    align="center"
                    label="状态"
                    width="80"
                    prop="status">
                <template v-slot="{row}">
                    <el-button size="mini" :type="row.status===1?'success':'info'" @click="statusHandle(row)">{{
                            row.status === 1 ? '启用' : '停用'
                        }}
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column
                    align="center"
                    label="备注"
                    width="200"
                    prop="mark">
                <template v-slot="{row}">
                    <el-input
                            type="textarea"
                            :autosize="true"
                            @change="changeMark(row)"
                            placeholder="请输入内容"
                            v-model="row.mark"
                            maxlength="20"
                            resize="none"
                            show-word-limit></el-input>
                </template>
            </el-table-column>
            <el-table-column
                    align="center"
                    label="操作"
                    fixed="right">
                <template v-slot="{ row }">
                    <el-button-group>
                        <el-button size="mini" type="primary" @click="editHandle(row)">编辑</el-button>
                        <el-button size="mini" type="warning" @click="delHandle(row.id)">删除</el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>

        <el-drawer
                title="记录解析"
                v-model="isDrawer"
                direction="rtl"
                :close-on-click-modal="false"
                destroy-on-close
                @open="openDrawer()"
                ref="drawer">

            <el-form
                    :model="rin"
                    status-icon
                    :rules="rules"
                    ref="ruleForm"
                    label-width="100px">

                <el-form-item label="域名" prop="zone">

                    <el-input
                            type="text"
                            v-model="rin.zone"
                            readonly
                            autocomplete="off"/>
                </el-form-item>


                <el-form-item label="主机名" prop="name">

                    <el-input
                            type="text"
                            v-model="rin.name"
                            autocomplete="off"/>

                </el-form-item>

                <el-form-item label="记录类型" prop="type">

                    <el-select v-model="rin.type" placeholder="请选择" class="form-width">
                        <el-option
                                v-for="item in types"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"/>
                    </el-select>

                </el-form-item>

                <el-form-item label="记录值" prop="value">

                    <el-input
                            type="text"
                            v-model="rin.value"
                            autocomplete="off"/>

                </el-form-item>
                <el-form-item label="TTL" prop="ttl">

                    <el-select v-model="rin.ttl" placeholder="请选择" class="form-width">
                        <el-option
                                v-for="item in ttls"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"/>
                    </el-select>

                </el-form-item>
                <el-form-item>
                    <el-affix position="bottom" :offset="20">
                        <el-button type="primary" @click="save()">提交</el-button>
                        <el-button @click="close()">返回</el-button>
                    </el-affix>
                </el-form-item>
            </el-form>

        </el-drawer>

    </div>
</template>

<script lang="ts">
import {defineComponent, inject, reactive, ref, toRefs} from 'vue'
import HttpClient from '@/classes/HttpClient'
import {RecordInDto, RecordOutDto} from '@/classes/dto/Record'
import {RuleItem} from 'async-validator'
import {Result} from '@/classes/BaseDto'
import {useRouter} from 'vue-router'
import {DomainInDto, DomainOutDto} from '@/classes/dto/Domain'
import {Paths} from '@/classes/Paths';
import ElTable from 'element-plus';
import ElButton, {
    ElAffix,
    ElButtonGroup,
    ElCol,
    ElDrawer,
    ElForm,
    ElFormItem,
    ElInput,
    ElOption,
    ElRow,
    ElSelect,
    ElTableColumn
} from 'element-plus';
import Base from '@/components/Base.vue';

interface RSelect {

    readonly label: string;

    readonly value: number | string;
}

export default defineComponent({
    name: 'Resolve',
    extends: Base,
    components: {
        ElForm,
        ElFormItem,
        ElSelect,
        ElOption,
        ElDrawer,
        ElTable,
        ElTableColumn,
        ElButtonGroup,
        ElButton,
        ElRow,
        ElCol,
        ElInput,
        ElAffix
    },
    setup() {

        const refForm = ref()

        const drawer = ref()

        const http: HttpClient | undefined = inject('$http')

        const ruleForm = ref()

        const records: RecordOutDto[] = []

        const router = useRouter()

        const query = router.currentRoute.value.query

        const indto = new DomainInDto()

        indto.id = query.id as string

        let domain = ref(new DomainOutDto())

        http?.request<DomainOutDto>(Paths.D_FIND, indto).then(res => {

            let d = res.data as DomainOutDto

            domain.value.name = d.name

            domain.value.id = d.id
        })

        const rin = new RecordInDto()

        const data = reactive({
            loading: false,
            visible: false,
            isDrawer: false,

            rin,
            records,
            ruleForm
        })

        return {
            ...toRefs(data),
            domain,
            http,
            refForm,
            drawer,
        }
    },
    created() {

        console.info('beforeCreate>>>============', this.http)

        this.list()

    },
    data() {

        const helpCard = 0

        const ttls: RSelect[] = [
            {value: 10 * 60, label: '10分钟'},
            {value: 30 * 60, label: '30分钟'},
            {value: 3600, label: '1小时'},
            {value: 12 * 3600, label: '12小时'},
            {value: 24 * 3600, label: '1天'}
        ]
        const types: RSelect[] = [
            {value: 'A', label: 'A      - 将域名指向一个IPV4地址'},
            {value: 'CNAME', label: 'CNAME  - 将域名指向另外一个域名'},
            {value: 'AAAA', label: 'AAAA   - 将域名指向一个IPV6地址'},
            {value: 'NS', label: 'NS     - 将子域名指定其他DNS服务器解析'},
            {value: 'MX', label: 'MX     - 将域名指向邮件服务器地址'},
            {value: 'SRV', label: 'SRV    - 记录提供特定的服务的服务器'},
            {value: 'TXT', label: 'TXT    - 文本长度限制512，通常做SPF记录（反垃圾邮件）'},
            {value: 'CAA', label: 'CAA    - CA证书颁发机构授权校验显性'},
            {value: 'URL', label: 'URL    - 将域名重定向到另外一个地址隐性'},
            {value: 'URL', label: 'URL    - 与显性URL类似，但是会隐藏真实目标地址'}
        ]
        const rules: { [key: string]: RuleItem } = {
            zone: {
                required: true
            },
            name: {
                required: true,
                message: '记录名称不符合规则',
                type: 'regexp',
                pattern: /^[\w]{1,60}$/

            },
            type: {
                required: true,
                message: '请选择解析类型.'
            },
            ttl: {
                required: true,
                message: '请选择生效时间.'
            },
            value: {
                required: true,
                message: 'IP格式错误',
                type: 'regexp',
                pattern: /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
            }

        }

        return {
            helpCard, types, rules, ttls, rtype: {}, rttl: {}
        }
    },
    methods: {

        fmtTtl(v: number): string {

            if (v / 3600 === 24) {
                return '1天'
            } else if (v / 3600 === 12) {
                return '12小时'
            } else if (v / 3600 === 1) {
                return '1小时'
            } else if (v / 60 === 30) {
                return '30分钟'
            } else {
                return '10分钟'
            }
        },

        list() {

            this.http?.request<RecordOutDto>(Paths.R_LIST)

                    .then((res: Result<RecordOutDto>) => {

                        this.records.length = 0

                        this.records = this.records.concat(res.data)
                    })

                    .catch(reason => {
                        console.info('=========>==', reason)
                    })
        },
        changeMark(item: RecordOutDto) {

            const indto = new RecordInDto()

            indto.mark = item.mark
            indto.id = item.id

            this.http?.request(Paths.R_MARK, indto)
                    .then(res => {
                        this.$message({
                            message: '修改成功!',
                            type: 'success'
                        })

                        this.list()
                    })
                    .catch(reason => {
                        this.$message({
                            message: '修改失败:' + reason,
                            type: 'error'
                        })
                    })
        },
        statusHandle(item: RecordOutDto) {

            const indto = new RecordInDto()

            indto.status = item.status === 1 ? 0 : 1
            indto.id = item.id

            this.http?.request(Paths.R_STATUS, indto)
                    .then(res => {
                        this.$message({
                            message: '修改成功!',
                            type: 'success'
                        })

                        this.list()
                    })
                    .catch(reason => {
                        this.$message({
                            message: '修改失败:' + reason,
                            type: 'error'
                        })
                    })
        },

        editHandle(item?: RecordOutDto) {
            this.isDrawer = true
            if (!item) {
                return
            }

            console.info('--addEditHandle->', item)
            this.rin.id = item.id
            this.rin.value = item.value
            this.rin.name = item.name
            this.rin.ttl = item.ttl
            this.rin.type = item.type

        },

        handleClose(done: any) {

            console.info('--->', typeof done, done.constructor.name)

            this.$confirm('确认关闭？')
                    .then((_: any) => {
                        done()
                    })
                    .catch((reason: string) => {
                        console.info('>>', reason)
                    })
        },
        delHandle(id: string) {
            console.info('==delHandle=>', id)

            this.$confirm('您确认删除解析?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {

                const dto = new RecordInDto()
                dto.id = id

                this.http?.request(Paths.R_DEL, dto)
                        .then(res => {
                            this.$message({
                                message: '删除成功!',
                                type: 'success'
                            })

                            this.list()
                        })
                        .catch(reason => {
                            this.$message({
                                message: '删除失败:' + reason,
                                type: 'error'
                            })
                        })
            })

        },
        save() {

            console.info('--save--0>', this.rin, this.ruleForm?.validate)

            this.ruleForm?.validate((r: boolean) => {

                if (!r) {

                    return
                }

                console.info('保存记录->', this.rin)

                this.http?.request(Paths.R_SAVE, this.rin)

                        .then((res) => {

                            console.info('===res=then=>', res)

                            this.$message({
                                message: '操作成功!',
                                type: 'success'
                            })
                            this.list()
                            this.close()

                        })
                        .catch((reason: string) => {

                            console.info('===res=catch=>', reason)

                            this.$message({
                                message: '添加失败:' + reason,
                                type: 'error'
                            })

                        }).finally(() => {
                    //  this.$emit('save', ['==>', Math.random()])
                })
            })
        },
        close() {
            this.isDrawer = false
            this.drawer.handleClose()
            this.rin = new RecordInDto()
            this.ruleForm.resetFields()
        },
        openDrawer() {
            this.rin.zone = this.domain.name
        }
    }
})
</script>

<style lang="scss" scoped>
.role-name-span + .role-name-span {
    margin-left: 10px;
}

.btns-right {
    text-align: right;
}

.form-width {
    width: 100%;
}

</style>
